//
//  ChatUserCacheInfo.swift
//  SitPosition
//
//  Created by apple on 2019/3/5.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import SQLite


/**
 * 环信用户昵称、头像缓存记录
 */
@objc class ChatUserCacheInfo : NSObject {
    
    // 表名+表字段
    fileprivate static let dbTable: String = "chatUserInfo"
    fileprivate static let table = Table(ChatUserCacheInfo.dbTable)
    fileprivate static let idField = Expression<String>("id")
    fileprivate static let nickNameField = Expression<String>("nickName")
    fileprivate static let avatarUrlField = Expression<String>("avatarUrl")
    
    // 属性
    @objc public let id: String
    @objc public let nickName: String
    @objc public let avatarUrl: String?
    
    // MARK: - Object lifecycle
    
    // CREATE TABLE IF NOT EXIST
    static func createIfNeeded(_ db: SQLite.Connection) throws -> Void {
        try db.run(ChatUserCacheInfo.table.create(ifNotExists: true) { (t) in
            t.column(ChatUserCacheInfo.idField, primaryKey: true)
            t.column(ChatUserCacheInfo.nickNameField)
            t.column(ChatUserCacheInfo.avatarUrlField)
        })
    }
    
    @objc public init(id: String, nickName: String, avatarUrl: String?) {
        self.id = id
        self.nickName = nickName
        self.avatarUrl = avatarUrl
    }
    
    // MARK: - Equatable
    
    public static func == (lhs: ChatUserCacheInfo, rhs: ChatUserCacheInfo) -> Bool {
        return lhs.id == rhs.id
    }
    
}


// MARK: - Private Methods

extension ChatUserCacheInfo {
    
    // 获取指定id对应的记录
    // @id - id值
    @objc static func query(by id: String) -> ChatUserCacheInfo? {
        guard let db: SQLite.Connection = Database.shared.db else {
            return nil
        }
        do {
            let query: SQLite.Table = ChatUserCacheInfo.table.filter(id == ChatUserCacheInfo.idField)
            if let row: Row = try db.pluck(query) {
                return ChatUserCacheInfo(id: row[ChatUserCacheInfo.idField],
                                         nickName: row[ChatUserCacheInfo.nickNameField],
                                         avatarUrl: row[ChatUserCacheInfo.avatarUrlField])
            } else {
                return nil
            }
        } catch {
            dbgPrint("filter chat user cache info occured error: \(error)")
            return nil
        }
    }
    
    // 更新指定id对应的记录
    @discardableResult
    @objc static func update(by id: String, nickName: String, avatarUrl: String?) -> Bool {
        guard let db: SQLite.Connection = Database.shared.db else {
            return false
        }
        
        do {
            // 先检查记录是否存在？
            if let _ = ChatUserCacheInfo.query(by: id) {
                // 更新记录
                let query: SQLite.Table = ChatUserCacheInfo.table.filter(id == ChatUserCacheInfo.idField)
                try db.run(query.update(ChatUserCacheInfo.nickNameField <- nickName,
                                         ChatUserCacheInfo.avatarUrlField <- (avatarUrl ?? "")))
            } else {
                // 创建记录
                let insert = ChatUserCacheInfo.table.insert(
                    ChatUserCacheInfo.idField <- id,
                    ChatUserCacheInfo.nickNameField <- nickName,
                    ChatUserCacheInfo.avatarUrlField <- (avatarUrl ?? "")
                )
                try db.run(insert)
            }
            return true
        } catch {
            return false
        }
    }
}
